const app = getApp();
const globalData = getApp().globalData;
const regeneratorRuntime = globalData.regeneratorRuntime;
const institutionservice = require("../../../apiservice/institution/institutionservise");
const userInfo = getApp().globalData.userInfo;
// pages/institution/list/list.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		competitorlist: [],
		region: ['湖南省', '长沙市', '芙蓉区'],
		keyname: '', //搜索关键词
		editShow: false,
		competitor: [],
		modname: '', //所修改的名称
		opentype: 'detail', //
		prevcompetitorId: '',
		showDistrict: false,
    //isJoinedIndex: 0,
    medicalTypeData: [{ "id": 1, "name": "社区卫生服务中心" }, { "id": 2, "name": "社区卫生服务站" }, { "id": 3, "name": "乡镇卫生院" }, { "id": 4, "name": "医院" }, { "id": 5, "name": "村卫生室" }, { "id": 6, "name": "其他" }],
    medicalTypeIndex: -1,
    medicalTypeName: "请选择",
    joinedType: [{ "id": 0, "name": "是" }, { "id": 1, "name": "否" }],
    joinedTypeIndex: 0,
    joinedTypeName: "请选择"
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {

		var that = this;
		const eventChannel = this.getOpenerEventChannel();
		eventChannel.on('openedInstitutionPage', function(e) {
			that.setData({
				opentype: e.data
			})
		});

		eventChannel.on('passHospitalId', function(e) {
			that.setData({
				prevcompetitorId: e.data ? e.data : ''
			})
			that.queryCompetitorByid();
		});


		if (userInfo) {
			var region = [];
			region.push(userInfo.new_provincename);
			region.push(userInfo.new_cityname);
			if (userInfo.new_areaname) {
				region.push(userInfo.new_areaname);
			} else {
				region.push('');
			}
			this.setData({
				region: region
			})
		}
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		if (!this.data.prevcompetitorId) {
			let competitor = {
				new_provincename: this.data.region[0],
				new_marketname: this.data.region[1],
				new_districtcountyname: this.data.region[2]
			}

			this.QueryCompetitor(competitor);
		}
	},


	queryCompetitorByid: async function() {
		wx.hideLoading({
			title: "加载中...",
			mask: true
		})
		let prevcompetitorId = this.data.prevcompetitorId;
		if (prevcompetitorId) {
			let result = await institutionservice.QueryCompetitorById(prevcompetitorId);
			let competitor = result.data;
			if (competitor.new_provincename &&
				competitor.new_marketname &&
				competitor.new_districtcountyname) {
				let region = [competitor.new_provincename,
					competitor.new_marketname,
					competitor.new_districtcountyname
				];
				this.setData({
					region: region
				})
				competitor = {
					new_provincename: region[0],
					new_marketname: region[1],
					new_districtcountyname: region[2]
				}
				//	debugger;
				this.QueryCompetitor(competitor);
			}
		}
		wx.hideLoading();
	},

	districtTap: function(e) {
		this.setData({
			showDistrict: true
		});
	},
	// 位置监听事件
	bindRegionChange: function(e) {

		this.setData({
			showDistrict: false
		});
		var provinceName = e.detail.currentTarget.dataset.province;
		var cityName = e.detail.currentTarget.dataset.city;
		var areaName = e.detail.currentTarget.dataset.area;
		var region = [];
		region.push(provinceName);
		region.push(cityName);
		region.push(areaName);
		this.setData({
			region: region
		});
		var competitor = {
			new_provincename: provinceName,
			new_marketname: cityName,
			new_districtcountyname: areaName,
			name: this.data.keyname
		}
		if (competitor.new_provincename == "全部")
			competitor.new_provincename = "";
		if (competitor.new_marketname == "全部")
			competitor.new_marketname = "";
		if (competitor.new_districtcountyname == "全部")
			competitor.new_districtcountyname = "";
		this.QueryCompetitor(competitor);
	},
  // onIsJoinedChange: function (e) {
  //   this.setData({
  //     isJoinedIndex: e.detail.index,
  //   });
  // },
  changeMedicalType: function (e) {
    var index = e.detail.value;
    this.setData({
      medicalTypeIndex: index,
      medicalTypeName: this.data.medicalTypeData[index].name
    });
  },
  changeJoinedType:function(e){
    var index = e.detail.value;
    this.setData({
      joinedTypeIndex: index,
      joinedTypeName: this.data.joinedType[index].name
    });

  },

	//搜索按钮
	onSearch: function(e) {
		var competitor = {
			new_provincename: this.data.region[0],
			new_marketname: this.data.region[1],
			new_districtcountyname: this.data.region[2],
			name: e.detail.searchKey
		}
		if (competitor.new_provincename == "全部")
			competitor.new_provincename = "";
		if (competitor.new_marketname == "全部")
			competitor.new_marketname = "";
		if (competitor.new_districtcountyname == "全部")
			competitor.new_districtcountyname = "";
		this.QueryCompetitor(competitor);
		this.setData({
			keyname: e.detail.searchKey
		});
		//}
	},
	editItem: function(e) {
		var competitor = {
			competitorid: e.currentTarget.dataset.id
		}
		console.log(competitor);
		this.QueryCompetitorById(competitor);
		this.setData({
			editShow: true,
		})
	},
	//取消修改
	onClose: function() {
		this.setData({
			editShow: false,
		});
	},
	//确定修改
	onSure: function(e) {
    if (this.data.competitor.name.replace(/\s+/g, '') == '') {
      wx.showToast({
        title: '请输入医疗机构名称',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (this.data.joinedTypeName == "请选择") {
      wx.showToast({
        title: '请选择是否医联体',
        icon: 'none',
        duration: 2000
      });
      return;

    }
    if (this.data.medicalTypeName == "请选择") {
      wx.showToast({
        title: '请选择医疗机构类型',
        icon: 'none',
        duration: 2000
      });
      return;

    }

		var competitor = {
			name: this.data.modname,
			competitorid: this.data.competitor.competitorid,
      new_type: this.data.medicalTypeData[this.data.medicalTypeIndex].id,
      new_iscoopmedicalcouplet: this.data.joinedTypeIndex == 0 ? true : false
		}
		this.SaveCompetitor(competitor);
		this.setData({
			editShow: false
		});
		//this.onLoad();
	},
	onChange: function(e) {

		console.log(e);
		this.setData({
			modname: e.detail
		});
	},
	enterDetail: function(e) {
		if (this.data.opentype == "choose") {
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.emit('HospitalEvent', {
				competitorName: e.currentTarget.dataset.name,
				competitorId: e.currentTarget.dataset.id
			});
			console.log(e);
			wx.navigateBack({
				delta: 1
			})
		}
	},
	//新增医疗机构
	addCompetitor: function() {
		wx.navigateTo({
			url: "../add/add?province=" + this.data.region[0] + "&city=" + this.data.region[1] + "&area=" + this.data.region[
				2]
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},



	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	// 根据省市区加载医疗机构
	QueryCompetitor: function(obj) {
		var that = this;
		institutionservice.QueryCompetitor(obj).then(function(success) {
			console.log(success);
			that.setData({
				competitorlist: success.data
			});
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	// 根据医疗机构ID获取医疗机构信息
	QueryCompetitorById: function(obj) {
		var that = this;
    that.setData({
      joinedTypeIndex: 0,
      joinedTypeName: "请选择"
    });
		institutionservice.QueryCompetitor(obj).then(function(success) {
			console.log(success);
			that.setData({
				competitor: success.data[0]
			});
      if (success.data[0].new_iscoopmedicalcouplet){
        that.setData({ joinedTypeIndex:0})
        that.setData({ joinedTypeName:that.data.joinedType[0].name})
      }
      else{
        that.setData({ joinedTypeIndex: 1 })
        that.setData({ joinedTypeName: that.data.joinedType[1].name })
      }

      if (success.data[0].new_type!=undefined){
        let typeIdx = 0;
        typeIdx = that.GetTypeIndex(success.data[0].new_type);
        that.setData({ medicalTypeIndex: typeIdx, medicalTypeName: that.data.medicalTypeData[typeIdx].name});
      }
      else{
        that.setData({ medicalTypeIndex: -1, medicalTypeName: "请选择" });
      }

		}).catch(function(ex) {
			console.log(ex);
		})
	},
  GetTypeIndex:function(type){
    let ret = -1;
    for (var i = 0; i < this.data.medicalTypeData.length;i++){
      if(type== this.data.medicalTypeData[i].id){
        ret= i;
        break;
      }
    }
    return ret;

  },
	// 修改或新增医疗机构
	SaveCompetitor: function(obj) {
		var that = this;
		var msg = '创建';
		if (obj.competitorid) {
			msg = '修改';
		}
    wx.showLoading({
      title: '提交中',
      mask:true
    })
		institutionservice.SaveCompetitor(obj).then(function(success) {
      wx.hideLoading();
			that.showResult(success.data, msg);
			that.onLoad();
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	showResult: function(res, msg) {
		var title = '';
		var icon = '';
		if (res.resultState == 1) {
			title = msg + '成功';
			icon = 'success';
		} else {
			title = msg + '失败';
			icon = 'none';
		}
		wx.showToast({
			title: title,
			icon: icon,
			duration: 2000
		});
	},
})
